﻿using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Tian.Common.Base;
using Tian.Common.Enums.FileEnum;
using Tian.Common.Sort;
using Tian.Common.Verify;

namespace software.winwpfs.develop
{
    /// <summary>
    /// MoveAndRenameFile.xaml 的交互逻辑
    /// </summary>
    public partial class MoveAndRenameFile : Page
    {
        public MoveAndRenameFile()
        {
            InitializeComponent();
        }
        private void ButFirstPath(object sender, RoutedEventArgs e)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog("请选择一个文件夹");
            dialog.EnsureReadOnly = true;
            dialog.IsFolderPicker = true;//可以选择文件夹
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if (string.IsNullOrEmpty(dialog.FileName))
                {
                    MessageBox.Show("文件夹路径不能为空", "提示");
                    return;
                }
                FirstPath.Text = dialog.FileName;
            }
        }

        private void ButEndPath(object sender, RoutedEventArgs e)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog("请选择一个文件夹");
            dialog.EnsureReadOnly = true;
            dialog.IsFolderPicker = true;//可以选择文件夹
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if (string.IsNullOrEmpty(dialog.FileName))
                {
                    MessageBox.Show("文件夹路径不能为空", "提示");
                    return;
                }
                EndPath.Text = dialog.FileName;
            }
        }
        private void BtnMoveFile(object sender, RoutedEventArgs e)
        {
            if (!CharVerify.IsNumber(NumberLength.Text.Trim()))
            {
                HandyControl.Controls.MessageBox.Error("数字长度错误！", "操作提示");
                return;
            }
            int length = Convert.ToInt32(NumberLength.Text.Trim());
            string number = StartNumber.Text.Trim();
            bool isdesc = (bool)IsDesc.IsChecked;
            int startnum = Convert.ToInt32(number);
            string startpath = FirstPath.Text.Trim();
            string endpath = EndPath.Text.Trim();
            if (endpath == "")
            {
                endpath = startpath;
            }
            //获取视频文件类型
            List<string> videoTypes = new List<string>();
            for (int i = 0; i < VideoType.SelectedItems.Count; i++)
            {
                ListBoxItem boxItem = (ListBoxItem)VideoType.SelectedItems[i];
                videoTypes.Add(boxItem.Content.ToString());
            }
            //获取图片文件类型
            List<string> imageTypes = new List<string>();
            for (int i = 0; i < ImageType.SelectedItems.Count; i++)
            {
                ListBoxItem boxItem = (ListBoxItem)ImageType.SelectedItems[i];
                imageTypes.Add(boxItem.Content.ToString());
            }
            //判断是否存在目录
            if (!Directory.Exists(startpath))
            {
                HandyControl.Controls.MessageBox.Error("初始文件路径不存在！", "操作提示");
                return;
            }
            //判断是否存在目录
            if (!Directory.Exists(endpath))
            {
                HandyControl.Controls.MessageBox.Error("最终文件路径不存在！", "操作提示");
                return;
            }

            List<DirectoryInfo> folders = fileHelper.GetAllFoldersInPath(startpath);
            bool ischild = (bool)IsChild.IsChecked;
            //是否包含子目录，如果包含子目录则输出文件路径就是本身路径
            //不包含子目录，如果输出路径没写则输出文件路径就是本身路径，否则就是填写的路径
            if (ischild)
            {
                for (int i = 0; i < folders.Count; i++)
                {
                    if (imageTypes.Count > 0)
                    {
                        TryMoveFiles(folders[i].FullName, folders[i].FullName, startnum, length, isdesc, FileEnum.Image, imageTypes);
                    }
                    if (videoTypes.Count > 0)
                    {
                        TryMoveFiles(folders[i].FullName, folders[i].FullName, startnum, length, isdesc, FileEnum.Video, videoTypes);
                    }

                }
            }
            else
            {
                if (imageTypes.Count > 0)
                {
                    TryMoveFiles(startpath, endpath, startnum, length, isdesc, FileEnum.Image, imageTypes);
                }
                if (videoTypes.Count > 0)
                {
                    TryMoveFiles(startpath, endpath, startnum, length, isdesc, FileEnum.Video, videoTypes);
                }
            }
            HandyControl.Controls.MessageBox.Success("导出成功！", "操作提示");
        }
        FileUtil fileHelper = new FileUtil();
        private void TryMoveFiles(string startpath, string endpath, int number, int length, bool desc, FileEnum fileEnum, List<string> fileType)
        {

            List<FileInfo> files = fileHelper.GetAllFilesInPath(startpath);
            if (files.Count == 0)
            {
                return;
            }
            FileSort fileIComparer = new FileSort();
            //筛选文件
            List<FileInfo> fileReady = files.Where(t =>
            {
                string[] list = t.Name.Split('.');
                string houzhui = list[list.Length - 1].ToLower();
                if (fileType.Contains(houzhui))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }).ToList();
            //文件排序
            if (desc)
            {
                fileIComparer.FileSortByNameDesc(ref fileReady);
            }
            else
            {
                fileIComparer.FileSortByNameAsc(ref fileReady);
            }
            switch (fileEnum)
            {
                case FileEnum.Image:
                    PerformMoveFiles(endpath, number, length, fileReady);
                    break;
                case FileEnum.Video:
                    PerformMoveFiles(endpath, number, length, fileReady, "v");
                    break;
                default:
                    break;
            }

        }
        //移动文件
        private void PerformMoveFiles(string path, int number, int length, List<FileInfo> files, string prefix = "")
        {
            for (int i = 0; i < files.Count; i++)
            {
                string newname = prefix;
                if (number == 1)
                {
                    newname += (i + number).ToString();
                }
                else
                {
                    newname += GetStringLength((i + number).ToString(), length);
                }
                string name = files[i].Name;
                string[] list = name.Split('.');
                string houzhui = list[list.Length - 1].ToLower();
                string allname = newname + "." + houzhui;
                files[i].MoveTo(path + Path.DirectorySeparatorChar + allname);
            }
        }

        public string GetStringLength(string value, int length)
        {
            string result = "";
            for (int i = 0; i < length; i++)
            {
                if (length - value.Length == 0)
                {
                    result = value;
                }
                else if (length - value.Length == 1)
                {
                    result = "0" + value;
                }
                else if (length - value.Length == 2)
                {
                    result = "00" + value;
                }
                else if (length - value.Length == 3)
                {
                    result = "000" + value;
                }
                else if (length - value.Length == 4)
                {
                    result = "0000" + value;
                }
            }
            return result;
        }
    }
}
